package com.atldy.commerce.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.atldy.commerce.account.BalanceInfo;
import com.atldy.commerce.filter.AccessContent;
import com.atldy.commerce.mapper.EcommerceBalanceMapper;
import com.atldy.commerce.pojo.EcommerceBalance;
import com.atldy.commerce.service.EcommerceBalanceService;
import com.atldy.commerce.vo.LoginUserinfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class EcommerceBalanceServiceImpl extends ServiceImpl<EcommerceBalanceMapper, EcommerceBalance>
        implements EcommerceBalanceService {

    @Autowired
    private EcommerceBalanceMapper balanceMapper;


    /**
     * @author: 唐多令
     * @date: 2021/8/13 22:48
     * @description: 根据当前用户id获取余额信息
     */
    @Override
    public BalanceInfo getCurrentBalanceByUserId() {
        Long userId = getUserId();
        BalanceInfo balanceInfo = new BalanceInfo(userId, 0L);
        EcommerceBalance balance = getEcommerceBalance(userId);
        if (balance != null) {
            balanceInfo = balance.toBalanceInfo();
        } else {
            //插入值
            balance = new EcommerceBalance();
            balance.setBalance(0L);
            balance.setUserId(userId);
            int i = balanceMapper.insert(balance);
            if (i != 1) {
                log.error(">>>>>生成余额失败");
            }
        }
        return balanceInfo;
    }


    /**
     * @author: 唐多令
     * @date: 2021/8/13 22:53
     * @param: [balanceInfo 需要扣减的余额]
     * @description: 扣减余额
     */
    @Override
    public BalanceInfo deductionsBalanceInfo(BalanceInfo balanceInfo) {
        log.info("开始扣减余额，参数为: [{}]", JSONUtil.formatJsonStr(JSONUtil.toJsonStr(balanceInfo)));
        if (balanceInfo == null && balanceInfo.getBalance() == null) {
            log.error("余额不能为空");
        }
        Long userId = getUserId();
        if (!userId.equals(balanceInfo.getUserId())) {
            throw new RuntimeException("请求异常，扣减余额失败");
        }
        //获取当前用户余额
        EcommerceBalance balance = getEcommerceBalance(userId);
        //获取余额
        Long sourceBalance = balance.getBalance();
        if (balance == null || sourceBalance < balanceInfo.getBalance()) {
            throw new RuntimeException("余额不足");
        }
        //扣减余额
        Long currentBalance = sourceBalance - balanceInfo.getBalance();

        //进行扣减
        EcommerceBalance ecommerceBalance = new EcommerceBalance();
        UpdateWrapper<EcommerceBalance> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id", userId);
        ecommerceBalance.setBalance(currentBalance);
        int update = balanceMapper.update(ecommerceBalance, wrapper);
        log.info("余额扣减结束：[{}]", JSONUtil.formatJsonStr(JSONUtil.toJsonStr(ecommerceBalance)));
        if (update != 1) {
            log.error(">>>>>余额扣减失败");
        }
        BalanceInfo info = ecommerceBalance.toBalanceInfo();
        info.setUserId(userId);
        return info;
    }

    private Long getUserId() {
        LoginUserinfo loginUserinfo = AccessContent.getLoginUserinfo();
        log.info("从本地缓存中取出用户信息：[{}]", JSONUtil.formatJsonStr(JSONUtil.toJsonStr(loginUserinfo)));
        return Convert.toLong(loginUserinfo.getId());
    }

    private EcommerceBalance getEcommerceBalance(Long userId) {
        QueryWrapper<EcommerceBalance> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        EcommerceBalance balance = balanceMapper.selectOne(wrapper);
        return balance;
    }
}





